package com.jhf.skypac_pda;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalDialog;
import com.jhf.skypac_pda.EventMessage.MessageEvent;
import com.jhf.skypac_pda.base.BaseActivity;
import com.jhf.skypac_pda.model.DialogCallback;
import com.jhf.skypac_pda.model.FinishedProductModel;
import com.jhf.skypac_pda.model.LzyResponse2;
import com.jhf.skypac_pda.model.StockLocationModel;
import com.jhf.skypac_pda.model.StockRegionModel;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okgo.OkGo;
import okgo.model.HttpHeaders;
import okgo.model.Response;

public class UpdateStockInActivity extends BaseActivity implements EMDKManager.EMDKListener, Scanner.DataListener, Scanner.StatusListener, BarcodeManager.ScannerConnectionListener {
    @BindView(R.id.textViewRollNumber)
    TextView textViewRollNumber;
    @BindView(R.id.textViewMaterialNumber)
    TextView textViewMaterialNumber;
    @BindView(R.id.textViewProductName)
    TextView textViewProductName;
    @BindView(R.id.textViewSpecification)
    TextView textViewSpecification;
    @BindView(R.id.textViewLength)
    TextView textViewLength;
    @BindView(R.id.textViewWeight)
    TextView textViewWeight;
    @BindView(R.id.tv_stock_in_time)
    TextView tvStockInTime;
    @BindView(R.id.et_warehouse)
    TextView etWarehouse;
    @BindView(R.id.et_warehouse_area)
    TextView etWarehouseArea;
    @BindView(R.id.et_warehouse_position)
    TextView etWarehousePosition;
    private FinishedProductModel finishedProductModel = new FinishedProductModel();
    //private String rollNum = "";

    private ArrayList<DialogMenuItem> stringItems = new ArrayList<>();
    private ArrayList<DialogMenuItem> stringLocationItems = new ArrayList<>();
    private ArrayList<StockRegionModel> stockRegionModels = new ArrayList<>();
    private ArrayList<StockLocationModel> stockLocationModels = new ArrayList<>();
    private int stockRegionPosition = 0;
    private int stockLocationPosition = 0;

    private AtomicBoolean initFlag = new AtomicBoolean(false);
    private EMDKManager emdkManagerOther = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    public ScannerInfo readScannerInfo;
    private boolean bSoftTriggerSelected = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();
    private boolean isSwitchWarehouseRegion = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_stock_in);
        ButterKnife.bind(this);
        finishedProductModel = (FinishedProductModel) getIntent().getSerializableExtra("finishedProductModel");
        //rollNum = getIntent().getStringExtra("rollNum");
        initData();
        initZebra(this);
    }

    private void initData() {
        //textViewRollNumber.setText(rollNum);
        textViewRollNumber.setText(finishedProductModel.getMaterialBatchCode());
        textViewMaterialNumber.setText(finishedProductModel.getMaterialCode());
        textViewProductName.setText(finishedProductModel.getMaterialName());
        textViewSpecification.setText(finishedProductModel.getMaterialSpec());
        textViewLength.setText(finishedProductModel.getProductionReportLength() + " m");
        textViewWeight.setText(finishedProductModel.getProductionReportNetWeight() + " Kg");
        tvStockInTime.setText(finishedProductModel.getInputTime());
        etWarehouse.setText(finishedProductModel.getStockRoomName());
        etWarehouseArea.setText(finishedProductModel.getStockRegionName());
        etWarehousePosition.setText(finishedProductModel.getStockLocationName());

        getInputStockRegion(finishedProductModel.getStockRoomCode());
        getInputStockLocation(finishedProductModel.getStockRoomCode(), finishedProductModel.getStockRegionCode());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 8) {
            // activity关闭，从栈中移除
            //appManager.finishActivity(this);
            if (UpdateStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
                Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show();
                Log.i("登录过期走到这里=========", "FeedingDetailActivity");
                Intent intent = new Intent(UpdateStockInActivity.this, LoginActivity.class);
                intent.putExtra("isUpdate", true);
                startActivity(intent);
            }
        }
    }

    @OnClick({R.id.tv_back, R.id.et_warehouse_area, R.id.et_warehouse_position, R.id.sign_in_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                deInitScanner();
                deInitBarcodeManager();
                if (emdkManagerOther != null) {
                    emdkManagerOther.release();
                    emdkManagerOther = null;
                    initFlag.set(false);
                }
                finish();
                break;
            case R.id.et_warehouse_area:
                final ActionSheetDialog dialog = new ActionSheetDialog(UpdateStockInActivity.this, stringItems, null);
                dialog.title("选择库区")//
                        .titleTextSize_SP(14.5f)//
                        .show();

                dialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //T.showShort(mContext, stringItems[position]);
                        etWarehouseArea.setText(stringItems.get(position).mOperName);
                        stockRegionPosition = position;

                        isSwitchWarehouseRegion = true;
                        getInputStockLocation(finishedProductModel.getStockRoomCode(), stockRegionModels.get(position).getStockRegionCode());

                        dialog.dismiss();
                    }
                });
                break;
            case R.id.et_warehouse_position:
                final ActionSheetDialog dialog2 = new ActionSheetDialog(UpdateStockInActivity.this, stringLocationItems, null);
                dialog2.title("选择库位")//
                        .titleTextSize_SP(14.5f)//
                        .show();

                dialog2.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //T.showShort(mContext, stringItems[position]);
                        etWarehousePosition.setText(stringLocationItems.get(position).mOperName);
                        stockLocationPosition = position;

                        //getInputStockLocation(etWarehouse.getText().toString().trim(), stockRegionModels.get(position).getStockRegionCode());

                        dialog2.dismiss();
                    }
                });
                break;
            case R.id.sign_in_button:
                upDate();
                break;
        }
    }

    public void initZebra(Context context) {
        boolean initResult = initFlag.compareAndSet(false, true);
        if (initResult) {
            XLog.i("ZEBRA初始化扫码设备");
            try {
                EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
                XLog.i("ZEBRA初始化结果" + results.statusCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            XLog.i("ZEBRA已经初始化");
        }

    }

    private void upDate() {
        if(TextUtils.isEmpty(etWarehouseArea.getText().toString().trim())){

            Toast.makeText(UpdateStockInActivity.this, "库区不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }
        if(TextUtils.isEmpty(etWarehousePosition.getText().toString().trim())){

            Toast.makeText(UpdateStockInActivity.this, "库位不能为空",Toast.LENGTH_SHORT).show();

            return ;
        }

        final NormalDialog dialog3 = new NormalDialog(UpdateStockInActivity.this);
        dialog3.content("是否确更新库位？")
                .btnNum(2)
                .btnText("取消", "确认")
                .title("库位更新确认")
                //.showAnim(mBasIn)//
                //.dismissAnim(mBasOut)//
                .show();
        dialog3.setCanceledOnTouchOutside(false);

        dialog3.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog3.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog3.dismiss();

                        //更新请求
                    }
                });
    }

    private void getInputStockRegion(String stockRoomCode) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse2<ArrayList<StockRegionModel>>>get(Urls.URL_GET_STOCK_REGION + "?pageNum=" + 1 + "&pageSize=" + 1000 + "&stockRoomCode=" + stockRoomCode)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse2<ArrayList<StockRegionModel>>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse2<ArrayList<StockRegionModel>>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                stockRegionModels = response.body().rows;
                                stringItems.clear();
                                for (StockRegionModel stockRegionModel :
                                        stockRegionModels) {
                                    DialogMenuItem dialogMenuItem = new DialogMenuItem(stockRegionModel.getStockRegionName(), 0);
                                    stringItems.add(dialogMenuItem);
                                }

                                /*finishedProductModel = response.body().data;
                                finishedProductModel.setMaterialBatchCode(data);
                                if (response.body().data.getStockIoOrderStatus().equals("approved")) {
                                    etWarehouse.setText(finishedProductModel.getStockRoomName());
                                    mList.clear();
                                    mList.add(finishedProductModel);
                                    if (null == mList || mList.size() == 0) {
                                        imgEmpty.setVisibility(View.VISIBLE);
                                    } else {
                                        imgEmpty.setVisibility(View.GONE);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    Intent intent = new Intent(FinishedProductStockInActivity.this, UpdateStockInActivity.class);
                                    intent.putExtra("finishedProductModel", (Serializable) finishedProductModel);
                                    //intent.putExtra("rollNum", data);
                                    startActivity(intent);
                                }*/
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse2<ArrayList<StockRegionModel>>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void getInputStockLocation(String stockRoomCode, String stockRegionCode){
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse2<ArrayList<StockLocationModel>>>get(Urls.URL_GET_STOCK_LOCATION + "?pageNum=" + 1 + "&pageSize=" + 1000 + "&stockRoomCode=" + stockRoomCode + "&stockRegionCode=" + stockRegionCode)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse2<ArrayList<StockLocationModel>>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse2<ArrayList<StockLocationModel>>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                stockLocationModels = response.body().rows;
                                stringLocationItems.clear();
                                for (StockLocationModel stockLocationModel :
                                        stockLocationModels) {
                                    DialogMenuItem dialogMenuItem = new DialogMenuItem(stockLocationModel.getStockLocationName(), 0);
                                    stringLocationItems.add(dialogMenuItem);
                                }

                                if (isSwitchWarehouseRegion) {
                                    //清空之前选择的库位
                                    etWarehousePosition.setText("");
                                    isSwitchWarehouseRegion = false;
                                }

                                /*finishedProductModel = response.body().data;
                                finishedProductModel.setMaterialBatchCode(data);
                                if (response.body().data.getStockIoOrderStatus().equals("approved")) {
                                    etWarehouse.setText(finishedProductModel.getStockRoomName());
                                    mList.clear();
                                    mList.add(finishedProductModel);
                                    if (null == mList || mList.size() == 0) {
                                        imgEmpty.setVisibility(View.VISIBLE);
                                    } else {
                                        imgEmpty.setVisibility(View.GONE);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    Intent intent = new Intent(FinishedProductStockInActivity.this, UpdateStockInActivity.class);
                                    intent.putExtra("finishedProductModel", (Serializable) finishedProductModel);
                                    //intent.putExtra("rollNum", data);
                                    startActivity(intent);
                                }*/
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse2<ArrayList<StockLocationModel>>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManagerOther = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
        enumerateScannerDevices();
    }

    @Override
    public void onClosed() {
        if (emdkManagerOther != null) {
            emdkManagerOther.release();
            emdkManagerOther = null;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(readScannerInfo);
                setDecoders();
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManagerOther.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
        // Add connection listener
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
    }

    private void deInitBarcodeManager() {
        if (emdkManagerOther != null) {
            emdkManagerOther.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
                scanner.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            scanner = null;
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = true;
                // Set EAN13
                config.decoderParams.ean13.enabled = true;
                // Set Code39
                config.decoderParams.code39.enabled = true;
                //Set Code128
                config.decoderParams.code128.enabled = true;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                e.printStackTrace();
            }
        }
    }

    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            XLog.i("enumerateScannerDevices size = " + deviceList.size());
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while (it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    XLog.i("scnInfo friendlyName=%s,isDefaultScanner=%s", scnInfo.getFriendlyName(), scnInfo.isDefaultScanner());
                    if (scnInfo.isDefaultScanner()) {
                        readScannerInfo = scnInfo;
                        deInitScanner();
                        initScanner();
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, BarcodeManager.ConnectionState connectionState) {
        String scannerName = "";
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        scannerName = scannerInfo.getFriendlyName();
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch (connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
        } else {
            bExtScannerDisconnected = false;
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        //if (FinishedProductStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
            if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
            for (ScanDataCollection.ScanData data : scanData) {
                XLog.i("扫码结果data = %s,type=%s", data.getData(), data.getLabelType());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //这时认为扫码的是库位，然后去判断库位是否是合法的（是否已加载，是否是存在的）
                        if (stockLocationModels == null || stockLocationModels.size() == 0) {
                            Toast.makeText(UpdateStockInActivity.this, "请先选择库区", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            for (int i = 0; i < stockLocationModels.size(); i++) {
                                if (data.getData().equals(stockLocationModels.get(i).getStockLocationCode())) {
                                    etWarehousePosition.setText(stockLocationModels.get(i).getStockLocationName());
                                    stockLocationPosition = i;
                                    return;
                                } else {
                                    continue;
                                }
                            }

                            Toast.makeText(UpdateStockInActivity.this, "没有所在库区的库位", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                //}
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                // set trigger type
                if (bSoftTriggerSelected) {
                    scanner.triggerType = Scanner.TriggerType.SOFT_ONCE;
                    bSoftTriggerSelected = false;
                } else {
                    scanner.triggerType = Scanner.TriggerType.HARD;
                }
                // submit read
                if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case WAITING:
                break;
            case SCANNING:
                break;
            case DISABLED:
                break;
            case ERROR:
                break;
            default:
                break;
        }
    }

    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        deInitScanner();
        deInitBarcodeManager();
        if (emdkManagerOther != null) {
            emdkManagerOther.release();
            emdkManagerOther = null;
            initFlag.set(false);
        }
    }*/

    /*@Override
    protected void onResume() {
        // The application is in foreground
        super.onResume();
        if (emdkManagerOther != null) {
            // Acquire the barcode manager resources
            initBarcodeManager();
            // Enumerate scanner devices
            enumerateScannerDevices();
            // Initialize scanner
            initScanner();
        }
    }

    @Override
    protected void onPause() {
        // The application is in background
        // Release the barcode manager resources
        super.onPause();
        deInitScanner();
        deInitBarcodeManager();
    }*/
}
